<template>
  <el-dialog :title="formDate.id?'编辑权限':'添加权限'" :visible="showDialog" @close="closeFn">
    <el-form ref="addDialog" label-width="120px" :rules="rules" :model="formDate">
      <el-form-item label="权限名称" prop="title">
        <el-input v-model="formDate.title" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="formDate.code" />
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="formDate.description" />
      </el-form-item>
      <el-form-item>
        <template>
          <el-row type="flex" justify="center">
            <el-button size="small" type="primary" @click="confirmFn">确定</el-button>
            <el-button size="small" @click="closeFn">取消</el-button>
          </el-row>
        </template>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addPermission, getPermissionById, editPermission } from '@/api/permission'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formDate: {
        title: '', // 标题
        code: '', // 标识
        description: '', // 描述
        pid: '0', // 父权限 id 没有的话就是 0
        type: '1' // 层级类型 1 或者 2
      },
      rules: {
        title: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入权限描述', trigger: 'blur' }
        ]
      }

    }
  },
  methods: {
    // 添加 编辑
    async confirmFn() {
      // 校验成功
      await this.$refs.addDialog.validate()
      if (this.formDate.id) {
        // 编辑
        await editPermission(this.formDate)
      } else {
        // 添加权限
        await addPermission(this.formDate)
      }
      // 关闭弹窗
      this.closeFn()
      // console.log(res)
      // 渲染列表
      this.$emit('updateEvent')
    },
    // 关闭弹窗函数
    closeFn() {
      // 关闭弹窗
      this.$emit('update:showDialog', false)
      // 清空数据
      this.formDate = {
        title: '', // 标题
        code: '', // 标识
        description: '', // 描述
        pid: '', // 父权限 id 没有的话就是 0
        type: '' // 层级类型 1 或者 2
      }
      // 清空校验
      this.$refs.addDialog.resetFields()
    },
    // 数据回显
    async editPermission(id) {
      const res = await getPermissionById(id)
      this.formDate = res.data
    }
  }
}
</script>

<style>
</style>
